package be.kdg.netpresentadmin;

import java.awt.event.*;
import java.io.*;
import java.rmi.*;

import javax.imageio.*;
import javax.swing.*;

import be.kdg.netpresent.*;

public class AdminMakePresentation extends AdminGUI implements ActionListener {

	// Default serial ID
	private static final long serialVersionUID = 1L;
	
	// Some constants used to manage user interactions.
	private static final int iPWD_QType_0 = 0;
	private static final int iPWD_QType_1 = 1;
	private static final int iPWD_QType_2 = 2;
	private static final int iPWD_QType_3 = 3;
	private static final int iPWD_QType_4 = 4;
	
	private PresentationInt presentation;
	private File[] images;
	private ImageIcon image;
	private boolean nextSlide;

	public AdminMakePresentation(NetPresentInt serverObject) throws IOException {

		super();
		boolean bNameInputCanceled = false;
		boolean bPWDInputCanceled = false;

		// Just initialize these here, outside of the try-catch with null,
		// in order to avoid warnings or errors about non initialized vars.
		String sPresentationName = null;
		String sPresentationPWD = null;

		// Voluntary try-catch to catch NullPointerExceptions due to canceling
		// the input-dialog as a whole. Used to add some user friendly behaviour.
		try {
			sPresentationName = JOptionPane.showInputDialog(null,
					"Geef een naam voor de presentatie dat u wilt aanmaken:",
					"NetPresent - MakePresentation", 1);

			while (sPresentationName.length() == 0) {
				sPresentationName = JOptionPane
						.showInputDialog(
								null,
								("Error: De naam kan niet leeg zijn!\n"
										+ "Geef een naam voor de presentatie dat u wilt aanmaken:"),
								"NetPresent - MakePresentation", 1);
			}
		} catch (NullPointerException e) {
			System.out.println("Cancelled Name input!!");
			bNameInputCanceled = true;
		}

		nextSlide = false;

		// First check for a valid name-entry. If not provided due to cancel, do
		// not attempt to read images. This extra check is needed. In an
		// combined if, although the if is not entered, the image-upload dialog
		// will still appear.
		if (!bNameInputCanceled)
		{	
			// At this point a valid, non-null presentation-name was entered,
			// now ask for a password. Voluntary try-catch to catch
			// NullPointerExceptions due to canceling the input-dialog as a
			// whole. Used to add some user friendly behaviour.
			try {
				sPresentationPWD = setupNewPWD(sPresentationName);
			} catch (NullPointerException e) {
				System.out.println("Cancelled PWD input!!");
				bPWDInputCanceled = true;
			}

			if (!bPWDInputCanceled) {
				// Up to this point, if a valid name and password was entered, there
				// will be an attempt to actually fill the presentation with content.
				// uploadAfbeeldingen() will create a popup where the user points to
				// a directory with all the picture files that need to be uploaded.
				// No files found or a cancel of the popup will end the creation.
				if (uploadAfbeeldingen()) {
					setVisible(true);
					presentation = (PresentationInt) serverObject
							.makePresentation(sPresentationName,
									sPresentationPWD);

					for (int i = 0; i < images.length; i++) {
						/*ImageIcon temp = new ImageIcon(ImageIO.read(images[i]));
						Image tmp = temp.getImage();
						Image tmpNew = tmp.getScaledInstance(800, 600, java.awt.Image.SCALE_SMOOTH);
						image = new ImageIcon(tmpNew);*/
						image = new ImageIcon(ImageIO.read(images[i]));
						super.infoPanel.clearText();
						super.imagePanel.updateImage(image);

						if (i == (images.length - 1)) {
							super.updateButtonText("Bewaar en ga terug naar hoofdmenu!");
						}

						while (!nextSlide) {
							image = new ImageIcon(ImageIO.read(images[i]));
							super.imagePanel.updateImage(image);
						}

						nextSlide = false;
					}
				} else {
					System.out.println("Er zijn geen afbeeldingen beschikbaar!");
				}
			}
		} else {
			System.out
					.println("MakePresentation canceled through the name dialog!");
		}
	}

	// Method which creates a file dialog popup. A list of all files within the
	// user-chosen directory will be made, after this, a picture filter will be applied
	// and a file-array with the result will be returned.
	public boolean uploadAfbeeldingen() {
		final JFileChooser fc = new JFileChooser();
		fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

		if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
			File directory = fc.getSelectedFile();
			images = directory.listFiles(new PictureFilter());
			return (images.length != 0);
		} else {
			return false;
		}
	}

	// Method with some extra functionality to get the GUI part a bit
	// realistic and user friendly. Popup-types are determined here.
	private String setupNewPWD(String sPresentationName) {
		boolean bPWDReEntryMatch = false;
		String sPresentationPWD = null;
		String sCheckPWD = null;

		// Initial question to enter a password...
		sPresentationPWD = managePwdPopUp(sPresentationName,
				AdminMakePresentation.iPWD_QType_0);

		while (!bPWDReEntryMatch) {
			// If password is empty loop until a valid password is entered.
			while (0 == sPresentationPWD.length()) {
				sPresentationPWD = managePwdPopUp(sPresentationName,
						AdminMakePresentation.iPWD_QType_1);
			};

			// Initial question to re-enter the previously entered pwd...
			sCheckPWD = managePwdPopUp(sPresentationName,
					AdminMakePresentation.iPWD_QType_2);

			// If password is empty loop until a valid password is entered.
			while (0 == sCheckPWD.length()) {
				sCheckPWD = managePwdPopUp(sPresentationName,
						AdminMakePresentation.iPWD_QType_3);
			};

			// Check if the 2 entered passwords match, exit if so, loop if
			// not...
			if (0 == sPresentationPWD.compareTo(sCheckPWD)) {
				bPWDReEntryMatch = true;
			} else {
				// Repeat question to enter a password...
				sPresentationPWD = managePwdPopUp(sPresentationName,
						AdminMakePresentation.iPWD_QType_4);
			}
		};

		return sPresentationPWD;
	}

	// Method with some extra functionality to get the GUI part a bit
	// realistic and user friendly. Popup-information is created here.
	private String managePwdPopUp(String sPresentationName, int iQuestionType) {
		String sPWDMsg = null;
		String sPWDTitle = null;

		// Preset all possible strings to be used.
		String sPWDMsg0 = "Geef een paswoord voor de presentatie: \""
				+ sPresentationName + "\"";
		String sPWDMsg1 = "Geef nogmaals het paswoord voor de presentatie: \""
				+ sPresentationName + "\"";
		String sPWDErr0 = "Error: Het paswoordveld mag niet leeg zijn!\n"
				+ "Geef een paswoord voor de presentatie: \""
				+ sPresentationName + "\"";
		String sPWDErr1 = "Error: Het paswoordveld mag niet leeg zijn!\n"
				+ "Geef nogmaals het paswoord voor de presentatie: \""
				+ sPresentationName + "\"";
		String sPWDErr2 = "De paswoorden kwamen niet overeen\n"
				+ "Geef een nieuw paswoord voor de presentatie: \""
				+ sPresentationName + "\"";

		String sPWDTitle0 = "Geef een paswoord aub...";
		String sPWDTitle1 = "Geef opnieuw het paswoord aub...";

		// Set the right message according to the desired question-type.
		switch (iQuestionType) {
		case AdminMakePresentation.iPWD_QType_0:
			sPWDMsg = sPWDMsg0;
			sPWDTitle = sPWDTitle0;
			break;

		case AdminMakePresentation.iPWD_QType_1:
			sPWDMsg = sPWDErr0;
			sPWDTitle = sPWDTitle0;
			break;

		case AdminMakePresentation.iPWD_QType_2:
			sPWDMsg = sPWDMsg1;
			sPWDTitle = sPWDTitle1;
			break;

		case AdminMakePresentation.iPWD_QType_3:
			sPWDMsg = sPWDErr1;
			sPWDTitle = sPWDTitle1;
			break;

		case AdminMakePresentation.iPWD_QType_4:
			sPWDMsg = sPWDErr2;
			sPWDTitle = sPWDTitle0;
			break;

		default:
			break;
		}

		// Password field created without specific length should let
		// the dialog be variable in its width. Confirmation needed.
		JPasswordField jpwdField = new JPasswordField();
		jpwdField.setEchoChar('*');

		// This array of object contains the string of the message to be
		// displayed and also the object "passwordfield"
		Object[] objArray0 = { sPWDMsg, jpwdField };

		// This must be an array of objects, so string will do. Here it
		// is used as the names of the buttons to appear and to set the
		// default button.
		String[] sPWDOptions = { "Enter" };

		// Generate the actual question-dialog here.
		JOptionPane.showOptionDialog(null, objArray0, sPWDTitle,
				JOptionPane.OK_OPTION, JOptionPane.QUESTION_MESSAGE, null,
				sPWDOptions, sPWDOptions[0]);

		return String.valueOf(jpwdField.getPassword());
	}

	@Override
	// Creating the GUI itself through the super-class.
	public void initialisePanels() {
		super.initialisePanels();
		super.infoPanel.setEditable(true);
	}

	@Override
	// Button-Action to be performed.
	public void actionPerformed(ActionEvent e) {
		try {
			presentation.makeSlide(image, super.infoPanel.getText());
			nextSlide = true;
		} catch (RemoteException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}
}
